<template>
    <div style="width: 100%; display: flex; justify-content: end">
        <el-select
                v-model="logListParams.handlerId"
                placeholder="请选择处理器"
                style="width: 200px"
                @change="(v)=>{
                    deleteParams.handlerId = v
                    getLogList()
                }"
                clearable
        >
            <el-option
                    v-for="item in dataHandlerList"
                    :key="item.id"
                    :label="item.remark"
                    :value="item.id"
            />
        </el-select>

        <div style="width: 400px; margin-left: 20px">
            <el-date-picker
                    v-model="timeValue"
                    @change="getLogList"
                    type="daterange"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :shortcuts="shortcuts"
                    :size="'default'"
            />
        </div>
        <el-popconfirm title="确认清除错误日志?" @confirm="clearLog(false)">
            <template #reference>
                <el-button
                    type="danger"
                    style="margin-left: 20px"
                >清除错误日志
                </el-button>
            </template>
        </el-popconfirm>

        <el-popconfirm title="确认清除正常日志?" @confirm="clearLog(true)">
            <template #reference>
                <el-button
                    type="primary"
                    style="margin-left: 20px"
                >清除正常日志
                </el-button>
            </template>
        </el-popconfirm>

    </div>
    <el-table
            :data="collectLogVO.list"
            style="width: 100%; height: 50vh; margin-top: 10px; margin-bottom: 10px"
            border
            :cell-style="{ 'text-align': 'center' }"
            :header-cell-style="{ 'text-align': 'center' }"
    >
        <el-table-column prop="handlerDataId" label="上报协议名称" min-width="25vw">
            <template #default="scope">
        <span>{{
            dataHandlerList.find((item) => item.id == scope.row.handlerDataId)?.remark
            }}</span>
            </template>
        </el-table-column>



        <el-table-column prop="saveData" label="解析协议结果数据" min-width="25vw"/>
        <el-table-column prop="sendData" label="上报数据包" min-width="25vw"/>
        <el-table-column prop="executeRes" label="响应结果" min-width="25vw"/>
        <el-table-column prop="executeStatus" label="处理状态" min-width="25vw">
            <template #default="scope">
                <el-tag
                    effect="light"
                    style="width: 3vw"
                    :type="scope.row.executeStatus == 0 ? 'danger' : 'success'"
                >
                    {{ scope.row.executeStatus == 0 ? "失败" : "成功" }}
                </el-tag>
            </template>
        </el-table-column>


        <el-table-column prop="createdAt" label="时间" min-width="25vw">
            <template #default="scope">
                <span>{{ timeFormatHandler(scope.row.createdAt) }}</span>
            </template>
        </el-table-column>
    </el-table>

    <div style="width: 100%; display: flex; justify-content: end">
        <el-pagination
                v-model:current-page="logListParams.pageNum"
                v-model:page-size="logListParams.pageSize"
                :page-sizes="[10, 15, 20]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="collectLogVO.total"
                @size-change="getLogList"
                @current-change="getLogList"
        />
    </div>
    <el-dialog
            v-model="dialog.show"
            draggable
            width="60vw"
            style="display: flex; flex-direction: column"
    >
        <template #header>
            <h3
                    style="
          width: 100%;
          text-align: center;
          margin: 0;
          border: 0;
          padding: 0;
        "
            >
                数据
            </h3>
        </template>
        <el-scrollbar height="55vh">
            <v-ace-editor
                    v-model:value="dialog.data!"
                    style="width: 100%; height: 50vh; font-size: 16px"
                    lang="json"
                    theme="monokai"
                    :options="options"
            />
        </el-scrollbar>
    </el-dialog>
</template>

<script setup lang="ts">
import {
    collectLogAPI,
    deleteCollectLogAPI,
    type CollectLogEntityListVO,
    type CollectLogParams,
    type DataHandler,
    type CollectLogDeleteParams
} from "@/api/solutionService";
import type {CollectTask} from "@/model/group";
import {reactive, ref, watch} from "vue";
import {View} from "@element-plus/icons-vue";
import {shortcuts} from "@/utils/time";
import {getDataHandlerAPI} from "../../../api/solutionService";
import {VAceEditor} from "vue3-ace-editor";
import {Ace} from "ace-builds";
import dayjs from "dayjs";
import {ElMessage} from "element-plus";
import {timeFormatHandler} from "@/utils/dataHandler";
// 采集器日志组件
defineOptions({
    name: "CollectLogView",
});

// 采集器日志参数
const {data} = defineProps<{
    data: CollectTask;
}>();

watch(
    () => data,
    () => {
        logListParams.collectTaskId = data.id!;
        timeValue.value = [
            new Date(new Date().setDate(new Date().getDate() - 6)),
            new Date().setHours(23, 59, 59),
        ];
        getDataHandlerList();
        getLogList();
    }
);

const options: Partial<Ace.EditorOptions> = reactive({
    useWorker: true, // 启用语法检查,必须为true
    enableBasicAutocompletion: true, // 自动补全
    enableLiveAutocompletion: true, // 智能补全
    enableSnippets: true, // 启用代码段
    showPrintMargin: false, // 去掉灰色的线，printMarginColumn
    highlightActiveLine: true, // 高亮行
    highlightSelectedWord: true, // 高亮选中的字符
    tabSize: 4, // tab锁进字符
    fontSize: 14, // 设置字号
    wrap: false, // 是否换行
    readonly: false, // 是否可编辑
    // minLines: 10, // 最小行数，minLines和maxLines同时设置之后，可以不用给editor再设置高度
    // maxLines: 50, // 最大行数
});

/**
 * 时间组件参数
 */
const timeValue = ref([
    new Date(new Date().setDate(new Date().getDate() - 6)),
    new Date().setHours(23, 59, 59),
]);

/**
 * 采集器日志搜索参数
 */
const logListParams = reactive<CollectLogParams>({
    collectTaskId: 0,
    pageNum: 1,
    pageSize: 10,
    handlerId: undefined,
    startTime:
        new Date(new Date().setDate(new Date().getDate() - 6))
            .toISOString()
            .split("T")[0] + " 00:00:00",
    endTime: new Date().toISOString().split("T")[0] + " 23:59:59",
});

/**
 * 展示采集器日志
 */
const collectLogVO = ref<CollectLogEntityListVO>({
    list: [],
    total: 0,
    loading: false,
});

/**
 * 获取采集器日志
 */
async function getLogList() {
    timeValue.value[0] = new Date(timeValue.value[0]).setHours(0, 0, 0, 0);
    timeValue.value[1] = new Date(timeValue.value[1]).setHours(23, 59, 59, 59);
    logListParams.startTime = new Date(timeValue.value[0]).getTime().toString();
    logListParams.endTime = new Date(timeValue.value[1]).getTime().toString();
    collectLogVO.value.loading = true;
    const {
        data: {list, total},
    } = await collectLogAPI(logListParams).finally(() => {
        collectLogVO.value.loading = false;
    });
    if (list != null) {
        list.forEach((item) => {
            item.saveData = JSON.stringify(
                item.saveData,
                (key, value) => {
                    try {
                        return JSON.parse(value);
                    } catch (e) {
                        return value;
                    }
                },
                2
            );
        });
        collectLogVO.value.list = list ?? [];
        collectLogVO.value.total = total;
    }else {
        collectLogVO.value.list = [];
    }
}

/** 日志列表 */
const dataHandlerList = ref<DataHandler[]>([]);

/** 数据弹窗  */
const dialog = reactive({
    show: false,
    data: "",
});

/**
 * 获取处理器列表
 */
async function getDataHandlerList() {
    const {
        data: {list},
    } = await getDataHandlerAPI({
        collectTaskId: data.id!,
        pageNum: 1,
        pageSize: 999999,
    });
    // list?.forEach((item) => {
    //   item.otherInfo = JSON.stringify(
    //     item.otherInfo,
    //     (key, value) => {
    //       try {
    //         return JSON.parse(value);
    //       } catch (e) {
    //         return value;
    //       }
    //     },
    //     2
    //   );
    // })

    dataHandlerList.value = list ?? [];
}

/**
 * 清除日志
 */
const deleteParams = ref<CollectLogDeleteParams>({
    handlerId: 0,
    status: false,
})
async function clearLog(status: boolean) {
    if(deleteParams.value.handlerId===0){
        ElMessage.warning("请先选择处理器");
    }
    deleteParams.value.status = status;
    const res = await deleteCollectLogAPI(deleteParams.value);
    if (res.code === 200) {
        ElMessage.success("操作成功");
    }
    await getLogList();
}
</script>

<style scoped></style>
